<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model="user.name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.number="user.age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="user.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click.prevent="addfn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(obj, index) in list" :key="obj.id">
          <td>{{ obj.id }}</td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.sex }}</td>
          <td>
            <button @click.prevent="delfn(index)">删除</button>
            <button @click.prevent="editfn(obj, index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      user: {
        name: "",
        age: 0,
        sex: "",
      },
      editindex: null,
      list: [
        {
          id: 100,
          name: "咋",
          age: 18,
          sex: "男",
        },
        {
          id: 110,
          name: "咋",
          age: 18,
          sex: "男",
        },
      ],
    };
  },
  methods: {
    addfn() {
      // 增加功能
      if (this.editindex !== null) {
        // 如果点过编辑是修改
        this.$set(this.list, this.editindex, { ...this.user });
        // 将变量还是转为空
        this.editindex = null;
      } else {
        //如果没有转过就是新增
        this.user.id =
          this.list.length == 0 ? 100 : this.list[this.list.length - 1].id + 1;
        this.list.push({ ...this.user });
      }
      // 置空表单
      this.user.name = "";
      this.user.age = 0;
      this.user.age = "";
    },
    delfn(index) {
      // 删除功能
      this.list.splice(index, 1);
    },
    editfn(obj, index) {
      //点击修改  数据回填   得到修改的索引值
      this.editindex = index;
      this.user = { ...obj };
    },
  },
};
</script>
